<template>
  <div class="app-container">
    {{specRang}}
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float: right" @click="handleSearchList()" type="primary" size="small">查询结果</el-button>
        <!-- <el-button
          style="float: right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        ></el-button> -->
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="产品：">
            <el-select
              v-model="listQuery.object.productCode"
              placeholder="请选择产品"
              clearable
              @change="choseProduct(listQuery.object.productCode)"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.productCode"
                :label="item.productName"
                :value="item.productCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-for="item in specs" :key="item.id" :label="item.specName">
            <el-input v-model="specsSearchData[item.specCode]"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button class="btn-add" @click="addGoods()" size="mini">添加</el-button>
    </el-card>
    <div class="table-container">
      <el-dialog title="新增商品" :visible.sync="this.addGoodsPage.dialogVisible" width="40%">
        <el-form
          :model="productOptions"
          :rules="goodsrules"
          ref="addGoodsForm"
          label-width="120px"
          style="width: 400px"
          size="small"
        >
          <el-form-item label="产品：">
            <el-select
              v-model="goods.productCode"
              placeholder="请选择产品"
              clearable
              @visible-change="addGoodsPagechoseProduct(goods.productCode)"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.productCode"
                :label="item.productName"
                :value="item.productCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="item in this.addGoodsPage.product.specs"
            :key="item.id"
            :label="item.specName"
          >
            <el-select
              v-model="specRang[item.specCode]"
              placeholder="请选择参数值"
              @visible-change="initSpecRang(item.specCode)"
            >
              <el-option
                v-for="itemvalue in specRangSelector[item.specCode]"
                :key="itemvalue.id"
                :label="itemvalue.rangeValue"
                :value="itemvalue.rangeValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="goods.remarks"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addGoodsPage.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddGoodsConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="table-container">
      <el-table
        ref="goodsTable"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        border
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.goodsCode}}</template>
        </el-table-column>
        <el-table-column label="产品名称" width="100" align="center">
          <template slot-scope="scope">{{scope.row.productName}}</template>
        </el-table-column>
        <el-table-column
          v-if="specs !==undefined &specs !== null &&specs.length>0"
          label="规格"
          width="100"
          align="center"
        >
          <el-table-column v-for="item in specs" :key="item.id" :label="item.specName" width="120">
            <template slot-scope="scope">{{getSpecValue(scope.row.goodsSpec,item.specCode)}}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">{{scope.row.status}}</template>
        </el-table-column>
        <el-table-column label="创建人" width="100" align="center">
          <template slot-scope="scope">{{scope.row.creator}}</template>
        </el-table-column>
        <el-table-column label="创建时间" width="100" align="center">
          <template slot-scope="scope">{{scope.row.createDate}}</template>
        </el-table-column>
        <el-table-column label="更新人" width="100" align="center">
          <template slot-scope="scope">{{scope.row.updator}}</template>
        </el-table-column>
        <el-table-column label="更新时间" width="100" align="center">
          <template slot-scope="scope">{{scope.row.updateDate}}</template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template slot-scope="scope">
            <p>
              <el-button size="mini" @click="handleShowSpecRang(scope.$index, scope.row)">查看参数值</el-button>
              <el-button size="mini" @click="handleSpecAvi(scope.$index, scope.row)">启用</el-button>

              <el-button
                size="mini"
                type="danger"
                @click="handleSpecDis(scope.$index, scope.row)"
              >禁用</el-button>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>ti
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import {
  fetchList,
  getAllProducts,
  querySpecByProductCode,
  addSpecRang,
  fetchListSpecRang,
  addSpecRangValue,
  updateSpecRangValueAvailable,
  updateSpecRangValueDisable,
  updateSpecDisable,
  updateSpecAvailable,
  addGoodsService
} from "@/api/goods";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  object: { productCode: "", goodsSpec: [] }
};
const defaultspec = {
  specName: "",
  remarks: ""
};

const defaultProductspec = {
  productCode: ""
};

const defaultAddGoodsProduct = {
  productCode: ""
};
const defaultspecRangValue = {
  rangeValue: "",
  specCode: ""
};
const specRangValueStatus = {
  rangeCode: "",
  status: ""
};
const specStatus = {
  specCode: "",
  status: ""
};

export default {
  // name: "spec",
  name: "specInfoForm",
  props: {
    value: Object,
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      specpage: {
        dialogVisible: false
      },
      specRangpage: {
        dialogVisible: false,
        adddialogVisible: false,
        object: { specCode: "" }
      },
      productOptions: [],
      rules: {
        specName: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
          {
            min: 2,
            max: 140,
            message: "长度在 2 到 140 个字符",
            trigger: "blur"
          }
        ],
        remarks: [{ required: true, message: "请输入备注", trigger: "blur" }]
      },

      goodsrules: {
        productName: [
          { required: true, message: "请选择产品", trigger: "blur" }
        ],
        remarks: [{ required: false, message: "请输入备注", trigger: "blur" }]
      },
      rulesRangVlue: {
        rangeValue: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
          {
            min: 2,
            max: 140,
            message: "长度在 2 到 140 个字符",
            trigger: "blur"
          }
        ]
      },
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      specs: [],
      specsSearchData: {},
      addGoodsPage: {
        dialogVisible: false,
        product: { productCode: "", specs: [] }
      },
      goodsSpec: {
        specCode: "",
        specValue: ""
      },
      goods: {
        productName: "",
        goodsSpec: [],
        productCode: "",
        remarks: ""
      },
      specRangSelector: {},
      specRang: {}
    };
  },
  created() {
    this.getALLProduct();
  },
  watch: {},
  filters: {
    verifyStatusFilter(value) {
      if (value === 1) {
        return "审核通过";
      } else {
        return "未审核";
      }
    }
  },
  methods: {
    getList() {
      this.listLoading = true;
      this.listQuery.object.goodsSpec = [];
      for (let [key, value] of Object.entries(this.specsSearchData)) {
        var goodsSpec = {
          specCode: "",
          specValue: ""
        };
        goodsSpec.specCode = key;
        goodsSpec.specValue = value;
        this.listQuery.object.goodsSpec.push(goodsSpec);
      }

      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },

    getALLProduct() {
      getAllProducts().then(response => {
        if (response.code == 200) {
          this.productOptions = response.data;
          this.listQuery.object.productCode = this.productOptions[0].productCode;
          defaultProductspec.productCode = this.productOptions[0].productCode;
          querySpecByProductCode(defaultProductspec).then(res => {
            if (res.code === 200) {
              this.specs = res.data;
              this.getList();
            }
          });
        } else {
          this.$message({
            message: response.msg,
            type: "warning",
            duration: 1000
          });
          return;
        }
      });
    },
    choseProduct(val) {
      defaultProductspec.productCode = val;
      querySpecByProductCode(defaultProductspec).then(res => {
        if (res.code === 200) {
          this.specs = res.data;
          this.getList();
        }
      });
    },

    addGoodsPagechoseProduct(val) {
      defaultAddGoodsProduct.productCode = val;
      this.addGoodsPage.product.productCode = val;
      querySpecByProductCode(defaultAddGoodsProduct).then(res => {
        if (res.code === 200) {
          this.addGoodsPage.product.specs = res.data;
        }
      });
    },
    addGoods() {
      this.addGoodsPage.dialogVisible = true;
    },

    initSpecRang(val) {
      var param = { specCode: val };
      fetchListSpecRang(param).then(res => {
        this.$set(this.specRangSelector,val,res.data)
        console.log(this.specRangSelector);
      });
    },

    handleSpecDis(index, row) {
      debugger;
      specStatus.specCode = row.specCode;
      specStatus.status = "禁用";
      updateSpecDisable(specStatus).then(response => {
        if ((response.code = 200)) {
          this.getList().then(response => {
            if ((response.code = 200)) {
              this.list = response.data;
            }
          });
        } else {
          this.$message({
            message: response.msg,
            type: "warning",
            duration: 1000
          });
          return;
        }
      });
    },
    getSpecValue(val, specCode) {
      if (val == null) {
        return;
      }
      debugger;
      var array = val.filter(item => {
        if (item.specCode === specCode) {
          return item;
        }
      });
      if (array == undefined || array.length <= 0) {
        return;
      }
      return array[0].specValue;
    },
     handleAddGoodsConfirm(){
       debugger
       this.goods.goodsSpec=[];
        for (let [key, value] of Object.entries(this.specRang)) {
        var goodsSpectem = {
          specCode: "",
          specValue: ""
        };
        goodsSpectem.specCode = key;
        goodsSpectem.specValue = value;
        this.goods.goodsSpec.push(goodsSpectem);        
        }
        addGoodsService(this.goods).then(res=>{
          this.addGoodsPage.dialogVisible=false
          this.getALLProduct();
        })

        
     },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: "请选择操作类型",
          type: "warning",
          duration: 1000
        });
        return;
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: "请选择要操作的商品",
          type: "warning",
          duration: 1000
        });
        return;
      }
      this.$confirm("是否要进行该批量操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }
        switch (this.operateType) {
          case this.operates[0].value:
            this.updatePublishStatus(1, ids);
            break;
          case this.operates[1].value:
            this.updatePublishStatus(0, ids);
            break;
          case this.operates[2].value:
            this.updateRecommendStatus(1, ids);
            break;
          case this.operates[3].value:
            this.updateRecommendStatus(0, ids);
            break;
          case this.operates[4].value:
            this.updateNewStatus(1, ids);
            break;
          case this.operates[5].value:
            this.updateNewStatus(0, ids);
            break;
          case this.operates[6].value:
            break;
          case this.operates[7].value:
            this.updateDeleteStatus(1, ids);
            break;
          default:
            break;
        }
        this.getList();
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handlePublishStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updatePublishStatus(row.publishStatus, ids);
    },
    handleNewStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updateNewStatus(row.newStatus, ids);
    },
    handleRecommendStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updateRecommendStatus(row.recommandStatus, ids);
    },
    handleResetSearch() {
      this.selectProductCateValue = [];
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleDelete(index, row) {
      this.$confirm("是否要进行删除操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        ids.push(row.id);
        this.updateDeleteStatus(1, ids);
      });
    },
    handleUpdateProduct(index, row) {
      this.$router.push({ path: "/pms/updateProduct", query: { id: row.id } });
    },
    handleShowVerifyDetail(index, row) {
      console.log("handleShowVerifyDetail", row);
    },
    handleShowLog(index, row) {
      console.log("handleShowLog", row);
    },
    updatePublishStatus(publishStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("publishStatus", publishStatus);
      updatePublishStatus(params).then(response => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      });
    },
    updateNewStatus(newStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("newStatus", newStatus);
      updateNewStatus(params).then(response => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      });
    },
    updateRecommendStatus(recommendStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("recommendStatus", recommendStatus);
      updateRecommendStatus(params).then(response => {
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      });
    },
    updateDeleteStatus(deleteStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("deleteStatus", deleteStatus);
      updateDeleteStatus(params).then(response => {
        this.$message({
          message: "删除成功",
          type: "success",
          duration: 1000
        });
      });
      this.getList();
    }
  }
};
</script>
<style></style>


